package com.ys.security.nodb.config;

import com.ys.security.nodb.service.UserService;
import com.ys.security.nodb.vo.UserDO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>@description:</p>
 *
 * @author yangshuang
 * @version 1.0
 * @date 2018/5/10 19:29
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class AnyUserDetailsService implements UserDetailsService {

    private final UserService userService;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {

        UserDO userDO = new UserDO();
        userDO.setUserName("ys");
        userDO.setPassword("ys");
        userDO.setRoles("USER,ADMIN");
        List<SimpleGrantedAuthority> simpleGrantedAuthorities = createAuthorities(userDO.getRoles());
        return new User(userDO.getUserName(), userDO.getPassword(), simpleGrantedAuthorities);


    }

    /**
     * 权限字符串转化
     * <p>
     * 如 "USER,ADMIN" -> SimpleGrantedAuthority("USER") + SimpleGrantedAuthority("ADMIN")
     *
     * @param roleStr 权限字符串
     */
    private List<SimpleGrantedAuthority> createAuthorities(String roleStr) {
        String[] roles = roleStr.split(",");
        return Arrays.stream(roles).map(role -> new SimpleGrantedAuthority(role)).collect(Collectors.toList());
    }
}
